package cn.itcast.cd.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.itcast.cd.dao.IBaseDao;
import cn.itcast.cd.domain.Permission;
import cn.itcast.cd.domain.Role;
import cn.itcast.cd.domain.User;
import cn.itcast.cd.service.ISecretService;


public class SecretServiceImpl implements ISecretService {

	private IBaseDao userDao;
	
	public void setUserDao(IBaseDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public List<Role> getRoleByUser(User user) {
		String hql = "SELECT u.roles FROM User u WHERE u.id = ?";
		
		Object[] params = new Object[]{user.getId()};
		List list = userDao.queryEntity(hql, params);
		System.out.println(list);
		return list;
	}

	@Override
	public List<Permission> getPermissionByRole(Role role) {
		String hql = "SELECT r.permissions FROM Role r WHERE r.id = ?";
		Object[] params = new Object[]{role.getId()};
		List list= userDao.queryEntity(hql, params);
		if(list!=null && list.size()>0){
			for (Object object : list) {
				System.out.println(object);
			}
		}
		return null;
	}

	
	@Override
	public Permission getPermissionByName(String resourceName) {
		String hql = "SELECT p FROM Permission p WHERE p.resource = ?";
		Object[] params = new Object[]{resourceName};
		Permission p = (Permission) userDao.queryUniqueEntity(hql, params);
		
		return p;
	}

	@Override
	public Set<Permission> getPermissionByUser(User user) {
		String hql = "SELECT u.roles FROM User u WHERE u.id = ?";
		Object[] params = new Object[]{user.getId()};
		Set<Permission> p = null;
		
		List<Role> list= userDao.queryEntity(hql, params);
		if(list.size()>0){
			for (Role role : list) {
				 p = role.getPermissions();
			}
		}
		return p;
	}

}
